package com.example.demo.service.impl;

import com.example.demo.commen.ResultCode;
import com.example.demo.dao.BoardMapper;
import com.example.demo.exception.ApplicationException;
import com.example.demo.model.Board;
import com.example.demo.service.IBoardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j

public class BoardServiceImpl implements IBoardService {

    @Autowired
    private BoardMapper boardMapper;
    @Override
    public List<Board> getBoardsBySum(Long sum) {
       if(sum==null||sum<=0){
           throw  new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
       }

      List<Board> list = boardMapper.selectByNum(sum);
       if(list==null){
           throw  new ApplicationException("没有数据版块，需要联系管理员进行增添");
       }
       return list;
    }

    @Override
    public void addOneArticleById(Long id) {
        if(id==null||id<=0){
             throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }
        Board board = boardMapper.selectByPrimaryKey(id);
        if(board==null||board.getId()<=0){
            throw  new ApplicationException("版块不存在");
        }

        Board updateBoard = new Board();
        updateBoard.setId(board.getId());
        updateBoard.setArticleCount(board.getArticleCount()+1);
        int flag = boardMapper.updateByPrimaryKeySelective(updateBoard);

        if(flag!=1){
            throw  new ApplicationException(ResultCode.FAILED.getMessage());
        }
    }

    @Override
    public Board selectById(Long id) {
        if(id==null||id<=0){
            log.info("参数出错");
            throw  new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }

        Board board = boardMapper.selectByPrimaryKey(id);
        if(board==null){
            throw new ApplicationException("版块不存在");
        }
        return board;
    }

    @Override
    public void subOneArticleById(Long id) {
        if(id==null||id<=0){
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }
        Board board = boardMapper.selectByPrimaryKey(id);
        if(board==null||board.getId()<=0){
            throw  new ApplicationException("版块不存在");
        }

        Board updateBoard = new Board();
        updateBoard.setId(board.getId());
        updateBoard.setArticleCount(board.getArticleCount()-1);
        if(updateBoard.getArticleCount()<0){
            updateBoard.setArticleCount(0);
        }
        int flag = boardMapper.updateByPrimaryKeySelective(updateBoard);

        if(flag!=1){
            throw  new ApplicationException(ResultCode.FAILED.getMessage());
        }
    }
}
